package com.xiaolin.web.common.login;

import com.xiaolin.web.common.utils.JwtUtils;
import com.xiaolin.web.entity.User;
import com.xiaolin.web.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName LoginController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/9/29
 * @Version 1.0
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    /**
     * 用户登录
     * @param user 只要参数名与对象属性对应上，表单数据会自动封装成对象
     * @param response
     * @param request @RequestParam("username") String username, @RequestParam("password") String password
     * @return
     * @throws IOException
     */
    @RequestMapping("/login")
    public String login(User user, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String contentType = request.getContentType();
        System.out.println(contentType);
        Map<String, Object> map = new HashMap<>();
        if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())){
            map.put("msg","错误");
            return "error";
        }
        User one = userService.selectByName(user.getUsername());
        if(one ==null || !one.getUsername().equals(user.getUsername()) || !one.getPassword().equals(user.getPassword())){
            response.sendRedirect(request.getContextPath()+"/error.html");
            map.put("msg","错误");
            return "error";
        }
        response.sendRedirect(request.getContextPath()+"/index.html");
//        String token = jwtUtils.generateToken(one.getId());
//        map.put("msg","success");
//        map.put("token",token);
//        map.put("expire",jwtUtils.getExpire());
        return "index";
    }

}
